<template>
  <div class="course-list-container">
    <el-card class="course-list-card">
      <template #header>
        <div class="card-header">
          <h2>课程列表</h2>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索课程名称"
              clearable
              class="search-input"
              @clear="handleSearchClear"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="navigateToAdd">
              <el-icon><Plus /></el-icon> 添加课程
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredCourses"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="name" label="课程名称" min-width="120" />
        <el-table-column prop="teacher" label="授课教师" min-width="120" />
        <el-table-column prop="experimentCount" label="实验数量" width="100" align="center" />
        <el-table-column prop="classCount" label="班级数量" width="100" align="center" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleViewExperiments(scope.row)"
            >
              查看实验
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="filteredCourses.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredCourses.length"
        />
      </div>
    </el-card>

    <!-- 实验列表对话框 -->
    <el-dialog
      v-model="experimentsDialogVisible"
      title="课程实验列表"
      width="70%"
    >
      <el-table
        :data="courseExperiments"
        style="width: 100%"
        border
        v-loading="experimentsLoading"
      >
        <el-table-column prop="id" label="实验编号" width="100" />
        <el-table-column prop="name" label="实验名称" min-width="150" />
        <el-table-column prop="description" label="实验描述" min-width="200" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEditExperiment(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteExperiment(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer">
        <el-button @click="experimentsDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleAddExperiment">添加实验</el-button>
      </div>
    </el-dialog>

    <!-- 添加/编辑实验对话框 -->
    <el-dialog
      v-model="experimentFormDialogVisible"
      :title="isEditExperiment ? '编辑实验' : '添加实验'"
      width="500px"
    >
      <el-form
        ref="experimentFormRef"
        :model="experimentForm"
        :rules="experimentRules"
        label-width="100px"
      >
        <el-form-item label="实验编号" prop="id">
          <el-input v-model="experimentForm.id" placeholder="请输入实验编号" />
        </el-form-item>
        <el-form-item label="实验名称" prop="name">
          <el-input v-model="experimentForm.name" placeholder="请输入实验名称" />
        </el-form-item>
        <el-form-item label="实验描述" prop="description">
          <el-input
            v-model="experimentForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入实验描述"
          />
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="experimentFormDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExperimentForm" :loading="submitting">
          {{ isEditExperiment ? '保存修改' : '添加实验' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import logger from '@/utils/Logger'
import { courseApi, experimentApi } from '@/utils/api'

export default {
  name: 'CourseList',
  components: {
    Search,
    Plus
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const experimentFormRef = ref(null)

    // 状态
    const loading = ref(false)
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const experimentsDialogVisible = ref(false)
    const experimentsLoading = ref(false)
    const courseExperiments = ref([])
    const currentCourse = ref(null)
    const experimentFormDialogVisible = ref(false)
    const isEditExperiment = ref(false)
    const submitting = ref(false)
    const experimentForm = ref({
      id: '',
      name: '',
      description: '',
      courseId: ''
    })

    // 表单验证规则
    const experimentRules = {
      id: [
        { required: true, message: '请输入实验编号', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入实验名称', trigger: 'blur' },
        { min: 2, max: 50, message: '实验名称长度应为2-50个字符', trigger: 'blur' }
      ]
    }

    // 计算属性
    const filteredCourses = computed(() => {
      const courses = store.getters.getCourses
      if (!searchQuery.value) {
        return courses
      }

      return courses.filter(c =>
        c.name.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    })

    // 方法
    const loadCourses = async () => {
      loading.value = true
      try {
        // 从后端API获取课程数据
        const response = await courseApi.getAllCourses()

        // 处理响应数据
        const courses = response.map(course => ({
          id: course.id.toString(),
          name: course.name,
          teacher: course.teacher,
          experimentCount: course.experimentCount,
          classCount: 0 // 班级数量需要另外获取或者后端直接返回
        }))

        store.dispatch('setCourses', courses)
        logger.info('课程列表加载成功', { count: courses.length })
      } catch (error) {
        logger.error('加载课程列表失败', error)
        ElMessage.error('加载课程列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearchClear = () => {
      searchQuery.value = ''
    }

    const navigateToAdd = () => {
      router.push('/course/add')
    }

    const handleEdit = (row) => {
      router.push(`/course/edit/${row.id}`)
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除课程 "${row.name}" 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await store.dispatch('deleteCourse', row.id)
          ElMessage.success('课程删除成功')
          logger.info('课程删除成功', { courseId: row.id, courseName: row.name })
          // 重新加载课程列表
          loadCourses()
        } catch (error) {
          logger.error('删除课程失败', error)
          ElMessage.error('删除课程失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    const handleViewExperiments = async (row) => {
      currentCourse.value = row
      experimentsLoading.value = true
      experimentsDialogVisible.value = true

      try {
        // 从后端API获取实验数据
        const response = await experimentApi.getExperimentsByCourse(row.id)

        // 处理响应数据
        const experiments = response.map(experiment => ({
          id: experiment.id.toString(),
          name: experiment.name,
          description: experiment.description || `实验${experiment.experimentNumber}`,
          courseId: experiment.courseId.toString(),
          experimentNumber: experiment.experimentNumber
        }))

        courseExperiments.value = experiments
        logger.info('课程实验列表加载成功', { courseId: row.id, count: experiments.length })
      } catch (error) {
        logger.error('加载课程实验列表失败', error)
        ElMessage.error('加载课程实验列表失败')
      } finally {
        experimentsLoading.value = false
      }
    }

    const handleAddExperiment = () => {
      isEditExperiment.value = false
      experimentForm.value = {
        id: '',
        name: '',
        description: '',
        experimentNumber: courseExperiments.value.length + 1,
        courseId: currentCourse.value.id
      }
      experimentFormDialogVisible.value = true
    }

    const handleEditExperiment = (experiment) => {
      isEditExperiment.value = true
      experimentForm.value = { ...experiment }
      experimentFormDialogVisible.value = true
    }

    const handleDeleteExperiment = (experiment) => {
      ElMessageBox.confirm(
        `确定要删除实验 "${experiment.name}" 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          // 调用API删除实验
          await experimentApi.deleteExperiment(experiment.id)

          // 从实验列表中删除
          courseExperiments.value = courseExperiments.value.filter(e => e.id !== experiment.id)

          // 更新课程的实验数量
          const updatedCourse = {
            ...currentCourse.value,
            experimentCount: courseExperiments.value.length
          }
          await store.dispatch('updateCourse', { id: updatedCourse.id, courseData: updatedCourse })

          ElMessage.success('实验删除成功')
          logger.info('实验删除成功', { experimentId: experiment.id, experimentName: experiment.name, courseId: currentCourse.value.id })
        } catch (error) {
          logger.error('删除实验失败', error)
          ElMessage.error('删除实验失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    const submitExperimentForm = async () => {
      if (!experimentFormRef.value) return

      await experimentFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true

          try {
            if (isEditExperiment.value) {
              // 更新实验
              await experimentApi.updateExperiment(experimentForm.value.id, experimentForm.value)

              // 更新本地数据
              const index = courseExperiments.value.findIndex(e => e.id === experimentForm.value.id)
              if (index !== -1) {
                courseExperiments.value[index] = { ...experimentForm.value }
              }

              ElMessage.success('实验更新成功')
              logger.info('实验更新成功', { experimentId: experimentForm.value.id, experimentName: experimentForm.value.name })
            } else {
              // 添加实验
              const newExperiment = {
                name: experimentForm.value.name,
                description: experimentForm.value.description,
                experimentNumber: experimentForm.value.experimentNumber,
                courseId: currentCourse.value.id
              }

              // 调用API创建实验
              const createdExperiment = await experimentApi.createExperiment(newExperiment)

              // 更新本地数据
              if (createdExperiment) {
                courseExperiments.value.push(createdExperiment)
              }

              // 更新课程的实验数量
              const updatedCourse = {
                ...currentCourse.value,
                experimentCount: courseExperiments.value.length
              }
              await store.dispatch('updateCourse', { id: updatedCourse.id, courseData: updatedCourse })

              ElMessage.success('实验添加成功')
              logger.info('实验添加成功', { experimentName: newExperiment.name })
            }

            experimentFormDialogVisible.value = false
          } catch (error) {
            logger.error(isEditExperiment.value ? '更新实验失败' : '添加实验失败', error)
            ElMessage.error(isEditExperiment.value ? '更新实验失败' : '添加实验失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }

    // 生命周期钩子
    onMounted(() => {
      loadCourses()
    })

    return {
      loading,
      searchQuery,
      currentPage,
      pageSize,
      filteredCourses,
      experimentsDialogVisible,
      experimentsLoading,
      courseExperiments,
      currentCourse,
      experimentFormDialogVisible,
      isEditExperiment,
      experimentForm,
      experimentFormRef,
      experimentRules,
      submitting,
      handleSearchClear,
      navigateToAdd,
      handleEdit,
      handleDelete,
      handleViewExperiments,
      handleAddExperiment,
      handleEditExperiment,
      handleDeleteExperiment,
      submitExperimentForm
    }
  }
}
</script>

<style scoped>
.course-list-container {
  max-width: 1200px;
  margin: 0 auto;
}

.course-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.search-input {
  width: 250px;
  margin-right: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
